package com.sun.asyncimporttask.listner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.sun.asyncimporttask.dto.ImportErrorRecord;
import com.sun.asyncimporttask.dto.UserImportDTO;
import com.sun.asyncimporttask.entity.User;
import com.sun.asyncimporttask.exception.ExcelImportException;
import com.sun.asyncimporttask.mapper.UserMapper;
import com.sun.asyncimporttask.service.ImportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 用户数据导入监听器
 */
/**
 * 用户导入监听器
 */
@Slf4j
@RequiredArgsConstructor
public class UserImportListener extends AnalysisEventListener<UserImportDTO> {
    private final String taskId;
    private final ImportService importService;
    private final UserMapper userMapper;
    private int processedRows = 0;

    @Override
    public void invoke(UserImportDTO data, AnalysisContext context) {
        processedRows++;
        try {
            // 数据校验
            validateData(data, context.readRowHolder().getRowIndex());

            // 保存到数据库
            User user = new User()
                    .setUsername(data.getUsername())
                    .setAge(data.getAge())
                    .setAddress(data.getAddress());

            userMapper.insert(user);
            importService.incrementSuccess(taskId);

        } catch (ExcelImportException e) {
            // 记录错误信息
            importService.addErrorRecord(taskId,
                    new ImportErrorRecord(
                            context.readRowHolder().getRowIndex() + 1, // Excel行号从1开始
                            data,
                            e.getErrorCode(),
                            e.getMessage()
                    )
            );
            importService.incrementFail(taskId);
        }
    }

    /**
     * 数据校验
     */
    private void validateData(UserImportDTO data, int rowIndex) throws ExcelImportException {
        // 用户名校验
        if (StringUtils.isBlank(data.getUsername())) {
            throw ExcelImportException.validationError("用户名", "不能为空");
        }

        // 年龄校验
        if (data.getAge() == null) {
            throw ExcelImportException.validationError("年龄", "不能为空");
        } else if (data.getAge() <= 0 || data.getAge() > 120) {
            throw ExcelImportException.validationError("年龄", "必须1-120之间");
        }

        // 地址校验
        if (StringUtils.isBlank(data.getAddress())) {
            throw ExcelImportException.validationError("地址", "不能为空");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("任务[{}]完成，共处理{}行数据", taskId, processedRows);
    }
}